package com.tansty.security.handler;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tansty.security.mapper.UserMapper;
import com.tansty.security.pojo.Permission;
import com.tansty.security.pojo.ResultVO;
import com.tansty.security.pojo.Role;
import com.tansty.security.service.UserService;
import com.tansty.security.service.impl.UserServiceImpl;
import com.tansty.security.utils.JsonUtil;
import com.tansty.security.utils.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * description: 登录成功处理逻辑 <br>
 * date: 2021/8/3 14:54 <br>
 * author: ztz <br>
 * version: 1.0 <br>
 * @author Tansty
 */
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        UserMapper userMapper = SpringUtil.getBean(UserMapper.class);
        // 更新最后一次登录的时间
        User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        com.tansty.security.pojo.User userEntity = userMapper.selectOne(new QueryWrapper<com.tansty.security.pojo.User>().eq("user_name", userDetails.getUsername()));
        userEntity.setLastLogin(LocalDateTime.now());
        userMapper.update(userEntity,null);
        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write(JsonUtil.obj2String(new ResultVO("success",200,"登录成功")));
    }
}
